import { requestClient } from '#/api/request';

export namespace GenericTableApi {
  export interface TableData {
    [key: string]: any;
  }
  
  export interface QueryParams {
    pageNo?: number;
    pageSize?: number;
    tableName: string;
    configId?: number;
    dataSourceId?: number;
    [key: string]: any;
  }

  export interface PageResult<T = any> {
    list: T[];
    total: number;
  }

  export interface TableMetadata {
    tableName: string;
    columns: ColumnInfo[];
    primaryKey: string;
    displayName?: string;
    table?: any; // 保存完整的表信息
  }

  export interface ColumnInfo {
    javaField: string;
    title: string;
    javaType: string;
    jdbcType: string;
    nullable: boolean;
    primaryKey: boolean;
    searchable: boolean;
    editable: boolean;
    dictType?: string | null;
    width?: number;
    sortable?: boolean;
    // 兼容旧字段
    field?: string;
    columnName?: string;
    columnComment?: string;
    displayName?: string;
    formType?: string;
    listOperationResult?: boolean;
    createOperation?: boolean;
    updateOperation?: boolean;
  }
}

/**
 * 获取表数据分页
 */
export function getTableData(tableName: string, params: any) {
  return requestClient.get<GenericTableApi.PageResult<GenericTableApi.TableData>>(
    `/lowcode/generic/${tableName}/page`,
    { params }
  );
}

/**
 * 获取表配置信息
 */
export function getTableConfig(tableName: string) {
  return requestClient.get<GenericTableApi.TableMetadata>(
    `/lowcode/generic/${tableName}/config`
  );
}

/**
 * 创建表数据
 */
export function createTableData(tableName: string, data: GenericTableApi.TableData, dataSourceConfigId?: number) {
  const params = { dataSourceId: dataSourceConfigId !== undefined ? dataSourceConfigId : 1 };
  return requestClient.post(
    `/lowcode/generic/${tableName}/create`,
    data,
    { params }
  );
}

/**
 * 更新表数据
 */
export function updateTableData(tableName: string, data: GenericTableApi.TableData, dataSourceConfigId?: number) {
  const params = { dataSourceId: dataSourceConfigId !== undefined ? dataSourceConfigId : 1 };
  return requestClient.put(
    `/lowcode/generic/${tableName}/update`,
    data,
    { params }
  );
}

/**
 * 删除表数据
 */
export function deleteTableData(tableName: string, id: number | string, dataSourceConfigId?: number) {
  const params: any = { id };
  // 后端要的参数名是dataSourceId，不是dataSourceConfigId
  params.dataSourceId = dataSourceConfigId !== undefined ? dataSourceConfigId : 1;
  return requestClient.delete(
    `/lowcode/generic/${tableName}/delete`,
    { params }
  );
}

/**
 * 批量删除表数据
 */
export function batchDeleteTableData(tableName: string, ids: (number | string)[], dataSourceConfigId?: number) {
  const params: any = { ids: ids.join(',') };
  // 后端要的参数名是dataSourceId，不是dataSourceConfigId
  params.dataSourceId = dataSourceConfigId !== undefined ? dataSourceConfigId : 1;
  return requestClient.delete(
    `/lowcode/generic/${tableName}/batch-delete`,
    { params }
  );
}

/**
 * 导出表数据
 */
export function exportTableData(tableName: string, params: any, dataSourceConfigId?: number) {
  // 后端要的参数名是dataSourceId，不是dataSourceConfigId
  params = { ...params, dataSourceId: dataSourceConfigId !== undefined ? dataSourceConfigId : 1 };
  return requestClient.download(
    `/lowcode/generic/${tableName}/export`,
    params
  );
}

// ==================== Magic API 接口支持 ====================

/**
 * Magic API 响应处理 - 完全静默处理成功响应
 */
function handleMagicApiResponse<T>(request: Promise<T>): Promise<T> {
  return new Promise((resolve, reject) => {
    request
      .then((response) => {
        // 正常成功响应
        resolve(response);
      })
      .catch((error) => {
        // 检查是否是Magic API的正常响应（code: 200但被axios拦截器当作错误）
        if (error && typeof error === 'object' && error.code === 200 && error.message === 'success') {
          // 静默成功：直接resolve，不触发任何消息
          resolve(error.data as T);
          return;
        }
        
        // 真正的错误才reject
        reject(error);
      });
  });
}

/**
 * Magic API - 分页查询
 */
export function getTableDataMagic(tableName: string, params: any) {
  // Magic API: 分页参数放URL，查询条件放body
  const { page, size, ...searchConditions } = params;
  
  const urlParams = {
    page: page || 1,
    size: size || 10
  };
  
  const request = requestClient.post<GenericTableApi.PageResult<GenericTableApi.TableData>>(
    `/dev/${tableName}/page`,
    searchConditions,
    { 
      params: urlParams,
      headers: {
        'Content-Type': 'application/json',
        isEncrypt: false, // 明确禁用API加密
      }
    }
  );
  
  return handleMagicApiResponse(request);
}

/**
 * Magic API - 条件查询（无分页）
 */
export function queryTableDataMagic(tableName: string, params: any) {
  const request = requestClient.post<GenericTableApi.TableData[]>(
    `/dev/${tableName}/query`,
    params,
    {
      headers: {
        'Content-Type': 'application/json',
        isEncrypt: false, // 明确禁用API加密
      }
    }
  );
  return handleMagicApiResponse(request);
}

/**
 * Magic API - 新增数据
 */
export function createTableDataMagic(tableName: string, data: GenericTableApi.TableData) {
  const request = requestClient.post(
    `/dev/${tableName}/insert`,
    data,
    {
      headers: {
        'Content-Type': 'application/json',
      }
    }
  );
  return handleMagicApiResponse(request);
}

/**
 * Magic API - 更新数据
 */
export function updateTableDataMagic(tableName: string, data: GenericTableApi.TableData) {
  const request = requestClient.post(
    `/dev/${tableName}/update`,
    data,
    {
      headers: {
        'Content-Type': 'application/json',
      }
    }
  );
  return handleMagicApiResponse(request);
}

/**
 * Magic API - 删除数据（逻辑删除）
 */
export function deleteTableDataMagic(tableName: string, id: number | string) {
  const request = requestClient.get(
    `/dev/${tableName}/delete`,
    {
      params: { id },
      headers: {
        isEncrypt: false, // 明确禁用API加密
      }
    }
  );
  return handleMagicApiResponse(request);
}

/**
 * Magic API - 批量删除数据（逻辑删除）
 */
export function batchDeleteTableDataMagic(tableName: string, ids: (number | string)[]) {
  // Magic API 批量删除：使用 /batch-delete 端点，GET 方法，参数为 ids=1,2,3
  const request = requestClient.get(
    `/dev/${tableName}/batch-delete`,
    {
      params: { ids: ids.join(',') },
      headers: {
        isEncrypt: false, // 明确禁用API加密
      }
    }
  );
  return handleMagicApiResponse(request);
}

/**
 * Magic API - 物理删除数据
 */
export function removeTableDataMagic(tableName: string, id: number | string) {
  const request = requestClient.get(
    `/dev/${tableName}/remove`,
    {
      params: { id },
      headers: {
        isEncrypt: false, // 明确禁用API加密
      }
    }
  );
  return handleMagicApiResponse(request);
}

/**
 * Magic API - 批量物理删除数据
 */
export function batchRemoveTableDataMagic(tableName: string, ids: (number | string)[]) {
  // Magic API 批量物理删除：使用 /batch-remove 端点（如果存在）
  // 如果没有批量物理删除端点，则保持并发调用
  const removePromises = ids.map(id => removeTableDataMagic(tableName, id));
  return Promise.all(removePromises);
}

/**
 * Magic API - 导出表数据
 */
export function exportTableDataMagic(tableName: string, params?: any) {
  // Magic API 导出接口使用download方法
  return requestClient.download(
    `/dev/${tableName}/export`,
    params || {},
    {
      headers: {
        isEncrypt: false, // 明确禁用API加密
      }
    }
  );
}